package com.jianbo.proxy.core;

import java.io.File;
import java.util.Map;
import java.util.Set;

import org.smartboot.http.common.logging.Logger;
import org.smartboot.http.common.logging.LoggerFactory;
import org.smartboot.http.server.HttpRequest;

import com.jianbo.proxy.conf.PropertiesConf;
import com.jianbo.proxy.conf.jsconfig.StaticWebConf;
import com.jianbo.proxy.entity.HttpResponseMiddle;
import com.jianbo.proxy.util.ContentTypeUtil;
import com.jianbo.proxy.util.Debug;
import com.jianbo.proxy.util.FileUtil;

public class StaticWeb implements Web {

    private static StaticWeb instance;
    public static StaticWeb getInstance() {
        if(instance == null) {
            StaticWebConf staticWebConf = StaticWebConf.getInstance();
            StaticWeb staticWeb = new StaticWeb();
            staticWeb.setConf(staticWebConf.getStaticPath());
            staticWeb.welcome = PropertiesConf.getInstance().getWelcome();
            logger.info("welcome page by static web " + staticWeb.welcome);
            instance = staticWeb;
        }
        return instance;
    }

    private static Logger logger = LoggerFactory.getLogger(StaticWeb.class);

    private Map<String, String> staticPath;
    private String welcome;

    public Map<String, String> getStaticPath() {
        return staticPath;
    }

    @Override
    public boolean handle(String path, HttpRequest request, HttpResponseMiddle response) throws Exception {
        if(path.equals("/")) {
            if(welcome == null) {
                // return false;
                welcome = "/index.html";

            }
            path = welcome;
        }
        Debug.info("Static web path", path);
        // "/front" -> D:\aaa\test\
        // /front/index.html -> D:\aaa\test\index.html
        Set<String> mappingUrls = staticPath.keySet();
        for(String mappingUrl : mappingUrls) {
            // Debug.info("mappingUrl:" + mappingUrl);
            String basePathList = staticPath.get(mappingUrl);
            String[] basePathStrs = basePathList.split(",");
            for(String basePath : basePathStrs) {
            
            if(path.startsWith(mappingUrl)) {
                // 匹配成功

                // startsWith 替换，既然是startsWith匹配，那就是startsWith替换
                String resPath = path.substring(mappingUrl.length());
                
                if(resPath.equals("/")) {
                    resPath = "";
                }
                
                String fullPath = basePath + resPath;
                // fullPath = fullPath.substring(fullPath.indexOf("&"));
                
                // Debug.info("path", path);
                // Debug.info("resPath", resPath);
                Debug.info("Static web fullPath", fullPath);
                File file = new File(fullPath);

                if(!file.isFile()) {
                    // return false;
                    continue;
                }

                // Debug.info(fullPath);
                byte[] content = FileUtil.readBytesFast(fullPath);

                if(content != null) {
                    logger.info("resPath: " + resPath);
                    String type = FileUtil.fileType(fullPath);
                    String contentType = ContentTypeUtil.contentType(type);
                    response.setContentType(contentType);
                    response.write(content);
                    return true;
                }
            }
            }
        }
        return false;
    }

    public void setConf(Map<String, String> staticPath) {
        this.staticPath = staticPath;
        Debug.info("静态资源配置", staticPath);
        for(String mapping : staticPath.keySet()) {
            if(!mapping.endsWith("/")) {
                throw new RuntimeException("静态资源映射必须以/为结尾");
            }
        }
    }
    
}
